package cn.edu.neusoft.neufooddemo.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.edu.neusoft.neufooddemo.R;
import cn.edu.neusoft.neufooddemo.bean.Result;
import cn.edu.neusoft.neufooddemo.bean.Shop;
import cn.edu.neusoft.neufooddemo.bean.UserInfo;
import cn.edu.neusoft.neufooddemo.common.Constants;
import cn.edu.neusoft.neufooddemo.listener.RetrofitListener;
import cn.edu.neusoft.neufooddemo.model.ShopModel;
import cn.edu.neusoft.neufooddemo.model.UserModel;

import static android.view.View.GONE;

/*import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;*/

public class PurchaseActivity extends BaseActivity implements RetrofitListener{
    private static final String CITY = "大连";
    private TextView purchase_username, purchase_shopname, purchase_foodname,
            purchase_price, purchase_sum, purchase_ordertime, purchase, purchase_total;
    private Spinner purchase_suggesttime;
    private EditText purchase_adress, purchase_num;
    private ImageView purchase_return;
    private ImageButton purchase_num_reduce, purchase_num_add;
    private Intent intent;
    private UserModel userModel;
    private ShopModel shopModel;
    private String stime,address;
    private double total;
    private ListView lv_search_result;
    private boolean search_flag = false;
    private String selectedResult="";

    protected void initViews() {
        setLayout(R.layout.activity_purchase);
        purchase_username = (TextView) findViewById(R.id.purchase_username);
        purchase_shopname = (TextView) findViewById(R.id.purchase_shopname);
        purchase_foodname = (TextView) findViewById(R.id.purchase_foodname);
        purchase_price = (TextView) findViewById(R.id.purchase_price);
        purchase_num = (EditText) findViewById(R.id.purchase_num);
        purchase_sum = (TextView) findViewById(R.id.purchase_sum);
        purchase_ordertime = (TextView) findViewById(R.id.purchase_ordertime);
        purchase_total = (TextView) findViewById(R.id.purchase_total);
        purchase_suggesttime = (Spinner) findViewById(R.id.purchase_suggesttime);
        purchase_adress = (EditText) findViewById(R.id.purchase_adress);
        purchase_return = (ImageView) findViewById(R.id.purchase_return);
        purchase = (TextView) findViewById(R.id.purchase);
        purchase_num_reduce = (ImageButton) findViewById(R.id.purchase_num_reduce);
        purchase_num_add = (ImageButton) findViewById(R.id.purchase_num_add);
        lv_search_result = (ListView) findViewById(R.id.lv_search_result);
    }

    void initData() {
        intent = getIntent();
        purchase_foodname.setText(intent.getStringExtra("foodname"));
        purchase_price.setText("￥" + intent.getStringExtra("price"));
        purchase_num.setText("1");
        total=Double.parseDouble(intent.getStringExtra("price"));
        purchase_total.setText("￥" + total);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        purchase_ordertime.setText(formatter.format(curDate));
        purchase_sum.setText(intent.getStringExtra("price"));
        setSpinner(purchase_suggesttime, curDate);
        showUserInfo();
        showShopInfo();

      //  initMapLoactionInfo(purchase_adress.getText().toString(), null);
    }

    void initEvents() {
        purchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                purchase();
            }
        });
        purchase_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        purchase_num_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_purchase_num = purchase_num.getText().toString();
                if (!"1".equals(str_purchase_num)) {
                    double price = Double.parseDouble(intent.getStringExtra("price"));
                    int num = Integer.parseInt(str_purchase_num) - 1;
                    total = price * num;
                    purchase_num.setText("" + num);
                    purchase_total.setText("￥" + total);
                }
            }
        });
        purchase_num_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str_purchase_num = purchase_num.getText().toString();
                double price = Double.parseDouble(intent.getStringExtra("price"));
                int num = Integer.parseInt(str_purchase_num) + 1;
                total = price * num;
                purchase_num.setText("" + num);
                purchase_total.setText("￥" + total);
            }
        });
        purchase_adress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = purchase_adress.getText().toString();
               /* if (!"".equals(str) && search_flag) {
                    if(!str.equals(selectedResult))
                       initMapLoactionInfo(str, CITY);
                } else
                    lv_search_result.setVisibility(GONE);*/
            }

            @Override
            public void afterTextChanged(Editable s) {
                search_flag = true;
            }
        });
        lv_search_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                selectedResult = textView.getText().toString();
                purchase_adress.setText(selectedResult);
                search_flag = false;
                lv_search_result.setVisibility(GONE);

            }
        });
    }

    private void showUserInfo() {
        userModel = new UserModel();
        userModel.getUserById(getUser_id(),this);
    }


    @Override
    public void onSuccess(Object o, int flag) {
        if(flag== Constants.GETUSERBYID) {
            purchase_username.setText(((UserInfo)o).getUsername());
            purchase_adress.setText(((UserInfo)o).getAddress());
        }
        else if(flag==Constants.GETSHOPBYID)
        {
            purchase_shopname.setText(((Shop)o).getShopname());
        }
        else if(flag==Constants.INSERTORDER)
        {
            Result status=(Result)o;
            if (status.getSuccess().equals("1")) {
                intent = new Intent(PurchaseActivity.this, MyOrderActivity.class);
                startActivity(intent);
                showToast("购买成功");
            } else {
                showToast("购买失败");
            }
        }
    }

    @Override
    public void onFail() {
       showToast("网络连接错误");
    }

    private void showShopInfo() {
        shopModel = new ShopModel();
        shopModel.getShopById(intent.getStringExtra("shopid"),this);
    }

    private void purchase() {
       /* intent = new Intent(PurchaseActivity.this, PayActivity.class);
        intent.putExtra("foodname",purchase_foodname.getText().toString());
        intent.putExtra("foodprice",purchase_price.getText().toString());
        intent.putExtra("foodtotal",total+"");
        startActivity(intent);*/
       address=purchase_adress.getText().toString();
       userModel = new UserModel();
       userModel.insertOrder(getUser_id(),
                intent.getStringExtra("foodid"),
                purchase_num.getText().toString(),
                total + "",
                stime,address,this);
    }

    public void setSpinner(Spinner sp, Date date) {
        Date[] dates = new Date[5];
        for (int i = 0; i < dates.length; i++) {
            dates[i] = new Date(date.getTime() + (long) 30 * 60 * 1000 * (i + 1));
        }
        // 建立数据源
//        String[] mItems = getResources().getStringArray(R.array.suggesttime);
        final String[] mItems = new String[dates.length - 1];
        for (int i = 0; i < mItems.length; i++) {
            mItems[i] = dates[i].getHours() + ":" + formateMinute(dates[i].getMinutes()) + "----" +
                    dates[i + 1].getHours() + ":" + formateMinute(dates[i + 1].getMinutes());
        }

// 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mItems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//绑定 Adapter到控件
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                stime = mItems[pos];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }

    public String formateMinute(int minute) {
        if (minute < 10)
            return "0" + minute;
        else
            return minute + "";
    }

/*    public void initMapLoactionInfo(String keyWord, String cityCode) {
        PoiSearch.Query query = new PoiSearch.Query(keyWord, null, cityCode);
//keyWord表示搜索字符串，
//第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
//cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int rCode) {
                List<String> strs = new ArrayList<String>();
                ArrayList<PoiItem> items = poiResult.getPois();
                if (items != null && items.size() > 0) {
                    PoiItem item = null;
                    for (int i = 0, count = items.size(); i < count; i++) {
                        item = items.get(i);
                        strs.add(item.getTitle());
                    }
                    // 给ListView赋值，显示结果
                    lv_search_result.setVisibility(View.VISIBLE);
                    ArrayAdapter<String> array = new ArrayAdapter<String>(PurchaseActivity.this,
                            android.R.layout.simple_list_item_1, strs);
                    lv_search_result.setAdapter(array);
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }*/

}
